use password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString};
use pbkdf2::Pbkdf2;
use rand::rngs::OsRng;
use rand::RngCore;

pub const DEFAULT_N: u32 = 600000;

/// Used to store a new password.
pub fn hash_password(pw: &str) -> Result<String, password_hash::Error> {
    let salt = make_salt();
    let pwhash = Pbkdf2.hash_password(pw.as_bytes(), &salt)?.to_string();
    Ok(pwhash)
}

/// Used to check a password against a stored one.
pub fn check_password(pw: &str, store: &str) -> Result<(), password_hash::Error> {
    let parsed_hash = PasswordHash::new(store)?;
    Pbkdf2.verify_password(pw.as_bytes(), &parsed_hash)?;
    Ok(())
}

/// Makes a new salt string according to the Pbkdf2 rules.
fn make_salt() -> SaltString {
    let mut rng = OsRng;
    SaltString::generate(&mut rng)
}
